﻿using System.Text;
using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;
using BlazorLearn.Shared.Models;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

namespace BlazorLearn.ServerSideHost.Controllers;
[ApiController]
[Route("api/[controller]")]
public class AuthenticationController : ControllerBase
{
    [HttpPost("token")]
    public IActionResult GenerateTokenAsync(LoginViewModel model)
    {
        //查库


        UserInfo user = new()
        {
            UserName = model.UserName,
            Birthday = DateTime.Now,
        };

        //JWT: Header.Payload.Credential

        var key = "oqiejgfowirhgowirhgoewirwpeoigjw04owigf";
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

        var header = new JwtHeader(new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256));

        var userClaims = new List<Claim>();
        userClaims.Add(new(ClaimTypes.Name, user.UserName));
        userClaims.Add(new(ClaimTypes.DateOfBirth, user.Birthday.ToString()));

        var payload = new JwtPayload(userClaims);

        var token = new JwtSecurityToken(header, payload);

        var handler = new JwtSecurityTokenHandler();        

        string? jwtToken = handler.WriteToken(token);
        return Ok(jwtToken);
    }
}

class UserInfo
{
    public string? UserName { get; set; }
    public DateTime? Birthday { get; set; }
}